<template>
	<el-radio-group v-model="retuenValue" @change="onChange">
		<el-radio v-for="(item, index) in optionsList" :key="item[valueKey]" :label="item[valueKey]">
			<slot v-bind="item" :$index="index">{{ item[labelKey] }}</slot>
		</el-radio>
	</el-radio-group>
</template>

<script setup>
import { ref, computed, watch } from "vue"
import { useDictStore } from "/store/dict"

const props = defineProps(
	{
		modelValue: {
			type: [String, Number],
			default: "",
		},
		dict: {
			type: [String, Array],
		},
		label: {
			type: String,
		},
		value: {
			type: String,
		},
		disabled: {
			type: Boolean,
			default: false,
		},
	}
)

const emits = defineEmits(["update:modelValue", "change"])
const retuenValue = computed({
	get() {
		if (props.modelValue === null || props.modelValue === "") {
			return ""
		}
		return props.modelValue + ""
	},
	set(value) {
		emits("update:modelValue", value)
	},
})
const labelKey = computed(() => {
	if (props.label) {
		return props.label
	}
	return "name"
})
const valueKey = computed(() => {
	if (props.value) {
		return props.value
	}
	return "code"
})
const optionsList = ref([])
function refreshOptionsList() {
	if (typeof props.dict === "string") {
		const dictStore = useDictStore()
		dictStore.getDict(props.dict).then(resule => {
			optionsList.value = resule.map(item => ({ ...item, [valueKey.value]: item[valueKey.value] + "" }))
		})
		return
	}
	optionsList.value = props.dict.map(item => ({ ...item, [valueKey.value]: item[valueKey.value] + "" }))
}
refreshOptionsList()
watch(
	() => props.dict,
	() => {
		if (!props.dict) {
			return
		}
		refreshOptionsList()
	}
)

function onChange(value) {
	emits("change", value)
}
</script>

<style lang="scss" scoped></style>
